package 链表;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/5/11 21:24
 * @Description:
 */
public class 合并两个有序链表 {

    // l1 = [1,2,4], l2 = [1,3,4]
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null || list2 == null){
            return list1 == null ? list2 : list1;
        }
        ListNode head = list1.val < list2.val ? list1 : list2;
        ListNode left = head.next;
        ListNode right = head == list1 ? list2 : list1;
        ListNode current = head;

        while (left != null && right != null) {
            if(left.val < right.val){
                current.next = left;
                left = left.next;
            }else{
                current.next = right;
                right = right.next;
            }
            current = current.next;
        }
        current.next = left == null ? right : left;
        return head;
    }


    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }


}
